<?php namespace App\Admin\Access\OperationLog;

//基础条件
use App\Core\Repository\Criterias\FixedCriteria;

use Auth, Route;
use App\Admin\Access\Operation\Repository as OperationRepository;

trait Service {
    
    //基础服务
    use \App\Core\Service\Service;
    use \App\Core\Service\Services\Indexer;
    use \App\Core\Service\Services\Creater;
    use \App\Core\Service\Services\Updater;
    use \App\Core\Service\Services\Changer;
    use \App\Core\Service\Services\Deleter;
    use \App\Core\Service\Services\Detailer;
	
    //列表
    public function getOplogs(){
        $this->repository->getQuery()->orderBy('role_id', 'ASC');
        $rolesRaw = $this->repository->all('role_id', 'parent_id', 'sub_count', 'name', 'updated_at');
        return $this->success([
            'count' => $rolesRaw->count(),
            'data' => $this->repository->getTree($rolesRaw)
        ]);
    }
    
    //记录日志
	public function log(){
		$user = Auth::user();
		$params = Input::all();
		$operation = $this->getCurrentOperation();
		if(!$operation){
			return false;
		}
		DB::beginTransaction();
		try {
			$logObj = new OperateLog();
			$logObj->setProject();
                        $logObj->group_id = $operation->group_id;
			$logObj->operation_id = $operation->operation_id;
			$logObj->user_id = $user->user_id;
			$logObj->time = time();
			$logObj->ip = Input::ip();
			$logObj->data = json_encode($params, JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);
			$logObj->save();
		} catch (\Exception $exc) {
			DB::rollBack();
			return false;
		}
		DB::commit();
		return true;
	}
	
	//获取当前操作
	protected function getCurrentOperation(){
		$action = Route::currentRouteAction();
		if(strpos($action, '\\') !== false){//去掉命名空间
			$action = preg_replace('/.*\\\\/', '', $action);
		}
		$operation = with(new OperationRepository())->addCriteria(new FixedCriteria('code', $action))->first();
		if(!$operation){
			return false;
		}
		return $operation;
	}
}